package com.example.pieces;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.pieces.util.MyApplication;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.socket.client.Ack;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

public class ListViewActivity extends AppCompatActivity {
    private static final String TAG = "ListViewActivity";
    private ListView lv_listview;
    private int owerid;
    private MyAdapter adapter;
    private List<Map> mlist=new ArrayList<>();
    private Socket mSocket;
    private String[] ss;
    private ArrayList mList = new ArrayList();
    private List<Map> mListMap = new ArrayList();//截取得到的json数组。
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);
        //得到socket对象。
        MyApplication app = (MyApplication) getApplication();
        mSocket = app.getSocket();
        mSocket.connect();
        mSocket.on("user-joined",userjoined);
        mSocket.on("user-left",userleft);
        mSocket.on("user-list",userlist);
        mSocket.on("user-playing",userplaying);
        mSocket.on("user-ready",userready);
        mSocket.on("challenged",challenged);
        adapter=new MyAdapter();
        lv_listview= (ListView) findViewById(R.id.lv_listview);
        lv_listview.setAdapter(adapter);
        lv_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mlist.get(position).get("status").equals("ready")) {
                    mSocket.emit("challenge", mlist.get(position).get("id"), new Ack() {
                        @Override
                        public void call(Object... args) {

                        }
                    });
                    String clickid= (String) mlist.get(position).get("id");
                    int acl=Integer.parseInt(clickid);
                    if (acl==owerid) {
                        Toast.makeText(ListViewActivity.this, "不能挑战自己！", Toast.LENGTH_SHORT).show();
                    }else{
                        Intent i=new Intent(ListViewActivity.this,MainActivity.class);
                        startActivity(i);
                    }
                }else{
                    Toast.makeText(ListViewActivity.this, "该玩家正在对战！", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    /**
     * 服务器发送过来，被挑战方接收，并且进入游戏画面，执黑先行。
     */
    private Emitter.Listener challenged = new Emitter.Listener() {

        @Override
        public void call(final Object... args) {
            Log.e(TAG,"被挑战信息"+args[0].toString());
            String str=args[0].toString();
            final String[] arr=str.split("\"");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                    Intent i=new Intent(ListViewActivity.this,MainActivity.class);
                    i.putExtra("player",arr[1]);
                    startActivity(i);
                }
            });
        }
    };
    /**
     * 重新回到大厅，刷新用户状态为
     */
    private Emitter.Listener userready = new Emitter.Listener() {

        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject data = (JSONObject) args[0];
                    String result_id,id;
                    try {
                        id=data.getString("id");
                        for (int i=0;i<mlist.size();i++) {
                            JSONObject json=new JSONObject(mlist.get(i));
                            result_id=json.getString("id");
                            if (result_id.equals(id)) {
                                mlist.get(i).put("status","ready");
                            }
                        }
                    } catch (JSONException e) {
                        return;
                    }
                    adapter.notifyDataSetChanged();
                }
            });
        }
    };

    /**
     * 数据适配器
     */
    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mlist.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv=new TextView(ListViewActivity.this);
            String str= (String) mlist.get(position).get("status");
            tv.setText(""+mlist.get(position).get("name")+"   "+str);
            return tv;
        }
    }

    /**
     * 新用户加入，用户大厅刷新，此监听只监听新加入用户
     */
    private Emitter.Listener userjoined = new Emitter.Listener() {

        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject data = (JSONObject) args[0];
                    String username,status,id;
                    try {
                        Map<String, String> map = new HashMap<String, String>();
                        username = data.getString("name");
                        id = data.getString("id");
                        status = data.getString("status");
                        map.put("name",username);
                        map.put("status",status);
                        map.put("id",id);
                        mlist.add(map);
                        adapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        return;
                    }
                }
            });
        }
    };
    /**
     * 更新玩家状态为游戏状态playing
     */
    private Emitter.Listener userplaying = new Emitter.Listener() {

        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject data = (JSONObject) args[0];
                    String username,status,id;
                    try {
                        id=data.getString("id");
                        for (int i=0;i<mlist.size();i++) {
                            JSONObject json=new JSONObject(mlist.get(i));
                            String result_id=json.getString("id");
                            if (result_id.equals(id)) {
                                mlist.get(i).put("status","playing");
                            }
                        }
                    } catch (JSONException e) {
                        return;
                    }
                    adapter.notifyDataSetChanged();
                }
            });
        }
    };
    /**
     * 新用户离开，用户大厅刷新
     */
    private Emitter.Listener userleft = new Emitter.Listener() {

        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    JSONObject data = (JSONObject) args[0];
                    try {
                        String id=data.getString("id");
                        for (int i=0;i<mlist.size();i++) {
                            JSONObject json=new JSONObject(mlist.get(i));
                            String result_id=json.getString("id");
                            if (result_id.equals(id)) {
                                mlist.remove(i);
                            }else{

                            }
                        }
                        adapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        return;
                    }
                }
            });
        }
    };
    /**
     * 所有在线玩家，用户大厅刷新
     */
    private Emitter.Listener userlist = new Emitter.Listener() {

        @Override
        public void call(final Object... args) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                       JSONObject json = new JSONObject(args[0].toString());
                        String data=json.getString("data");
                        JSONObject userlist=new JSONObject(data);
                        getInfo(userlist.toString());
                        getArray();
                        String username,status,id;
                        for (int i=0;i<mListMap.size();i++) {
                            Map<String, String> map = new HashMap<String, String>();
                            String arr=mListMap.get(i).toString();
                            JSONObject mjson=new JSONObject(arr);
                            id = (mjson.getString("id"));
                            int aid=Integer.parseInt(id);
                            username=mjson.getString("name");
                            status=mjson.getString("status");
                            owerid=(owerid<=aid)?aid:owerid;
                            map.put("name",username);
                            map.put("status",status);
                            map.put("id", String.valueOf(id));
                            mlist.add(map);
                            adapter.notifyDataSetChanged();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSocket.disconnect();
    }
    private void getArray() {

        for (int i=0;i<mList.size()/7;i++) {
            //map集合放在循环内部，不然会覆盖掉前面的循环得到map。
            Map<String,String> map=new HashMap<>();
            String id= (String) mList.get(1 + i * 7);
            String idvalue= (String) mList.get(2 + i * 7);
            String status= (String) mList.get(3 + i * 7);
            String statusvalue= (String) mList.get(4 + i * 7);
            String name= (String) mList.get(5 + i * 7);
            String namevalue= (String) mList.get(6 + i * 7);
            map.put(id,idvalue);
            map.put(status,statusvalue);
            map.put(name,namevalue);
            mListMap.add(map);
        }
    }

    public void getInfo(String a){
        String[] arr=a.split(":|,");
        for (String s : arr) {
            ss=s.split("\\{|\\}");
            for (String sss : ss) {
                if (sss.equals("")) {

                }else{
                    mList.add(sss);
                }
            }
        }
    }
}
